﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Swashbuckle.AspNetCore.Filters;
using Microsoft.OpenApi.Models;
using Serilog;
using WCS_Core.Enums;
using System.Reflection;

namespace WCS_Core.Configs
{
    /// <summary>
    /// Swagger设置
    /// </summary>
    public static class SwaggerSetup
    {
        public static void AddClientSwaggerSetup(this IServiceCollection services)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));
            var apiName = "WCS服务端";
            services.AddSwaggerGen((s) =>
            {
                typeof(ApiVersions).GetEnumNames().ToList().ForEach(version =>
                {
                    s.SwaggerDoc(version, new OpenApiInfo
                    {
                        Version = version,
                        Title = $"{apiName} 接口文档",
                        Description = $"{apiName} HTTP API " + version,
                    });
                    s.OrderActionsBy(o => o.RelativePath);
                });
                try
                {
                    //生成API XML文档
                    var basePath = AppContext.BaseDirectory;
                    var xmlPath = Path.Combine(basePath, "WCS.xml");
                    s.IncludeXmlComments(xmlPath,true);
                }
                catch (Exception ex)
                {
                    Log.Error("Swagger", "Swagger生成失败，.xml丢失，请检查并拷贝。", ex);
                }

                // 开启加权小锁
                s.OperationFilter<AddResponseHeadersFilter>();
                s.OperationFilter<AppendAuthorizeToSummaryOperationFilter>();

                // 在header中添加token，传递到后台
                s.OperationFilter<SecurityRequirementsOperationFilter>();

                // 必须是 oauth2
                s.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}（注意两者之间是一个空格）\"",
                    Name = "Authorization",//jwt默认的参数名称
                    In = ParameterLocation.Header,//jwt默认存放Authorization信息的位置(请求头中)
                    Type = SecuritySchemeType.ApiKey
                });

            });
        }

    }
}
